package com.astrocsr.business;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.astrocsr.domain.bean.TblParameters;
import com.astrocsr.domain.web.ParametersInfo;

@Service("systemManager")
@Transactional(value = "transactionManager", propagation = Propagation.REQUIRED)
public class SystemManager extends BaseManager {

	/** 
	 *  get Parameter by Type and Code
	 */
	public ParametersInfo getParameters(String paramType, String paramCode) throws Exception {

		ParametersInfo parametersInfo = null;

		TblParameters tblParameters = new TblParameters();
		tblParameters.setParamType(paramType);
		tblParameters.setParamCode(paramCode);
		
		TblParameters result = getParametersDAO().getTblParameters(tblParameters);

		if (result != null) {

			// copy fields to display
			parametersInfo = new ParametersInfo();
			parametersInfo.setMerName(result.getMerName());
			parametersInfo.setParamType(result.getParamType());
			parametersInfo.setParamCode(result.getParamCode());
			parametersInfo.setParamName(result.getParamName());
			parametersInfo.setParamValue(result.getParamValue());

		}
		return parametersInfo;
	}
	
	public void updateParameter(ParametersInfo parametersInfo)
			throws Exception {

		if (parametersInfo != null	&& !StringUtils.isEmpty(parametersInfo.getParamType())
									&& !StringUtils.isEmpty(parametersInfo.getParamCode())) {

			TblParameters tblParameters = new TblParameters();
			tblParameters.setParamType(parametersInfo.getParamType());
			tblParameters.setParamCode(parametersInfo.getParamCode());
			List<TblParameters> listParameters = getParametersDAO().listTblParameters(tblParameters);
			
			// init object to update db
			tblParameters = new TblParameters();
			BeanUtils.copyProperties(parametersInfo, tblParameters);
			tblParameters.setCreatedDate(new Date());
			
			if (listParameters != null && listParameters.size() > 0) {
				// update
				getParametersDAO().updateTblParameters(tblParameters);
			} else {
				// add
				getParametersDAO().saveTblParameters(tblParameters);
			}
		}
	}
}